package com.qqtop10.manager.service.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.qqtop10.manager.dao.GoodsDetailedMapper;
import com.qqtop10.manager.dao.GoodsMapper;
import com.qqtop10.manager.model.Category;
import com.qqtop10.manager.model.Express;
import com.qqtop10.manager.model.Goods;
import com.qqtop10.manager.model.GoodsDetailed;
import com.qqtop10.manager.model.PagingArgs;
import com.qqtop10.manager.model.Shop;
import com.qqtop10.manager.model.SpecialPrice;
import com.qqtop10.manager.model.Result;
import com.qqtop10.manager.service.BuildHtmlService;
import com.qqtop10.manager.service.CategoryService;
import com.qqtop10.manager.service.ExpressService;
import com.qqtop10.manager.service.ShopService;
import com.qqtop10.manager.service.SpecialPriceService;
import com.qqtop10.manager.utils.FolderPath;
import com.qqtop10.manager.utils.FreemarkerUtil;
import com.qqtop10.manager.utils.UrlPath;

import freemarker.template.Configuration;
import freemarker.template.Template;

/**
 * 
 * @author Jovi-林兆维
 * @date 2015年5月30日
 * @version 1.0
 *
 */
@Service("buildHtmlService")
public class BuildHtmlServiceImpl implements BuildHtmlService {
	private static final Configuration Configuration = new Configuration();
	private static final HashMap<String, Template> Templates = new HashMap<>();

	private Logger logger = LoggerFactory.getLogger(BuildHtmlServiceImpl.class);

	private List<Category> allCategory = null;
	
	@Autowired
	private GoodsMapper goodsMapper;

	@Autowired
	private GoodsDetailedMapper goodsDetailedMapper;

	@Autowired
	private CategoryService categoryService;

	@Autowired
	private ShopService shopService;

	@Autowired
	private ExpressService expressService;

	@Autowired
	private SpecialPriceService specialPriceService;

	private static final Object TemplatesLook = new Object();

	static {
		try {
			File file = new File(FolderPath.getTemplatePath());
			if (!file.exists()) {
				file.mkdirs();
			}
			Configuration.setDirectoryForTemplateLoading(file);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	private static Template getTemplate(String name) {
		synchronized (TemplatesLook) {
			Template r = Templates.get(name);
			if (r != null) {
				return r;
			}
			try {
				r = Configuration.getTemplate("/" + name, "UTF-8");
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
			Templates.put(name, r);
			return r;
		}
	}

	public void buildPage(String path, String name, String out, Object map) {
		File outFile = null;
		if (path == null) {
			outFile = new File(FolderPath.getRootPath(), out);
		} else {
			outFile = new File(path, out);
		}
		if (!outFile.exists()) {
			try {
				outFile.createNewFile();
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
		}
		try (FileOutputStream output = new FileOutputStream(outFile);
				OutputStreamWriter writer = new OutputStreamWriter(output, "UTF-8")) {
			getTemplate(name).process(map, writer);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public Result buildGoodsPage(String uuid) {
		Result result = null;
		FreemarkerUtil fu = null;
		ObjectMapper objectMapper = null;
		Map<String, Object> root = null;
		Map<String, List<String>> attrsMap = null;
		Map<String, String> attrs = null;
		Map<String, String> pics = null;
		Goods goods = null;
		Category category = null;
		List<SpecialPrice> spList = null;
		GoodsDetailed goodsDetailed = null;
		Shop shop = null;
		List<Express> expressList = null;
		List<String> skukey = null;
		try {
			result = new Result(1, "生成商品类型成功");
			fu = new FreemarkerUtil();
			root = new HashMap<>();
			objectMapper = new ObjectMapper();
			attrsMap = new HashMap<>();
			skukey = new ArrayList<>();
			// 根据商品uuid获取商品
			goods = goodsMapper.selectByUuid(uuid);
			if (goods.getsku() == null) {
				goods.setsku("");
			}
			category = categoryService.selectByUuid(goods.getCategory_uuid());
			// 获取该商品的特价信息
			spList = specialPriceService.selectByGoodsUuid(new String[] { uuid });
			// 根据商品uuid获取商品详细
			goodsDetailed = goodsDetailedMapper.selectByGoodsUuid(uuid).get(0);
			// 获取该商品的属性
			attrs = objectMapper.readValue(goods.getAttributes(), Map.class);
			// 解析属性
			for (String key : attrs.keySet()) {
				String value = attrs.get(key);
				attrsMap.put(key, Arrays.asList(value.split(",")));
				skukey.add(key);
			}
			// 获取该商品的图片
			pics = objectMapper.readValue(goodsDetailed.getPicture(), Map.class);
			// 获取该商品的商店
			shop = shopService.selectByUuid(goods.getShop_uuid());
			// 获取该商品支持的快递
			expressList = expressService.selectByUuids(Arrays.asList(goods.getExpress_uuids().split(",")));
			root.put("goods", goods);
			if (spList != null && spList.size() != 0) {
				root.put("limited_number", spList.get(0).getLimited_number());
				root.put("specialPrice", spList.get(0).getSpecial_price());
				root.put("end_time", spList.get(0).getEnd_time().getTime());
			}
			root.put("goodsDetailed", goodsDetailed);
			root.put("category_uuid", category.getUuid());
			root.put("category_name", category.getName());
			root.put("category_name2", URLEncoder.encode(category.getName(), "UTF8"));
			root.put("attrs", attrsMap);
			root.put("pics", pics);
			root.put("shop", shop);
			root.put("expressList", expressList);
			root.put("url_home", UrlPath.HOME);
			root.put("skukey", skukey);
			// 文件保存路径
			File file = new File(FolderPath.getGoodsPath());
			if (!file.exists()) {
				file.mkdirs();
			}
			fu.fprintGoods("goods.html", root, file.getPath(), uuid + ".html");
			result.setCode(1);
			result.setMsg("生成商品页面成功！");
			logger.info("生成商品页面成功！");
		} catch (Exception e) {
			e.printStackTrace();
			result.setCode(500);
			result.setMsg("生成商品页面失败！");
			logger.error("生成商品页面失败！");
		}

		return result;
	}

	@Override
	public Result buildClassMenu() {
		Result result = null;
		List<Category> parentCategory = null;
		StringBuffer classMenu = null;
		FileOutputStream fos = null;
		try {
			result = new Result(1, "生成商品类型成功");
			fos = new FileOutputStream(FolderPath.getJSPath() + "classmenu.js");
			classMenu = new StringBuffer();
			allCategory = categoryService.selectAll();
			parentCategory = new ArrayList<>();
			for (Category category : allCategory) {
				if (category.getParentId() == 0) {
					parentCategory.add(category);
				}
			}
			classMenu.append("document.writeln('");
			for (Category category : parentCategory) {
				StringBuffer item = new StringBuffer();
				item.append("<li>");
				item.append("<span class=\"link\"><i class=\"iconfont\">" + category.geticon() + "</i> <a href=\"#\">"
						+ category.getName() + "</a></span>");
				// item.append(category.getName() + "</a></div>");
				item.append("<div class=\"nav-pop\">");
				for (Category c : allCategory) {
					if (c.getParentId().equals(category.getId())) {
						item.append(getSubItem(c));
					}
				}
				item.append("</div></li>");
				classMenu.append(item);
			}
			classMenu.append("');");
			fos.write(classMenu.toString().getBytes("UTF8"));
			fos.close();
		} catch (Exception e) {
			e.printStackTrace();
			result.setCode(500);
			result.setMsg("生成商品类型失败：" + e.getMessage());
		}
		return result;
	}
	

	private StringBuffer getSubItem(Category category) throws UnsupportedEncodingException {
		StringBuffer subItem = new StringBuffer();
		subItem.append("<dl>");
		subItem.append("<dt>" + category.getName() + "</dt>");
		subItem.append("<dd>");

		for (Category c : allCategory) {
			if (c.getParentId().equals(category.getId())) {
				subItem.append("<a target=\"_blank\" href=\"");
				subItem.append(UrlPath.HOME + "/goodslist.html?category_uuid=" + c.getUuid());
				subItem.append("&category=" + URLEncoder.encode(c.getName(), "UTF8"));
				subItem.append("\">" + c.getName() + "</a>");
			}
		}
		subItem.append("</dd></dl>");
		return subItem;
	}
/*
	private List<Category> getCategoryList() {
		List<Category> categoryList = null;
		Category category = null;
		PagingArgs pagingArgs = null;
		try {
			pagingArgs = new PagingArgs();
			category = new Category();
			category.setLevel_type(2);
			pagingArgs.set_limit(20);
			pagingArgs.set_offset(0);
			categoryList = categoryService.all(category, pagingArgs);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return categoryList;
	}*/
	
	
}
